<template>
    <div>
        <!-- 新增弹出框 -->
        <el-dialog title='新增' :visible.sync='addVisible' width='50%'>
            <el-form ref='addForm' :rules='addRule' :model='addForm' label-width='150px'>

                <el-form-item label='商品编号：' prop='productCode'>
                    <el-input v-model='addForm.productCode' type='text'></el-input>
                </el-form-item>
                <el-form-item label='商品名称：' prop='productName'>
                    <el-input v-model='addForm.productName' type='text'></el-input>
                </el-form-item>
                <el-form-item label='商品销售价（元）：' prop='productMoney'>
                    <el-input v-model='addForm.productMoney' type='number'></el-input>
                </el-form-item>
<!--                <el-form-item label='库存数：' prop='stock'>-->
<!--                    <el-input v-model='addForm.stock' type='number'></el-input>-->
<!--                </el-form-item>-->
                <el-form-item label='单位：' prop='speck'>
                    <el-input v-model='addForm.speck' type='text'></el-input>
                </el-form-item>
<!--                <el-form-item label='仓库号：' prop='warehouseCode'>-->
<!--                    <el-input v-model='addForm.warehouseCode' type='text'></el-input>-->
<!--                </el-form-item>-->
                <el-form-item label='展示图：' prop='productUrl'>
                    <el-upload
                        class='avatar-uploader'
                        :http-request='handleUploadImg'
                        action='url'
                        :show-file-list='false'
                        :before-upload='beforeAvatarUpload'>
                        <img v-if='imageUrl' :src='imageUrl' class='avatar'>
                        <i v-else class='el-icon-plus avatar-uploader-icon'></i>
                    </el-upload>
                </el-form-item>


            </el-form>

            <span slot='footer' class='dialog-footer'>
                        <el-button @click='addVisible = false'>取 消</el-button>
                        <el-button type='primary' @click="saveAdd('addForm')">确 定</el-button>
                    </span>
        </el-dialog>

    </div>
</template>

<script>
import global from '../common/Global';
export default {
    name: 'addProduct',
    data() {
        const validatorNum = (rule, value, callback) => {
            if (!value) {
                callback();
            } else if (!/^(([0-9]+)|([0-9]+\.[0-9]{0,2}))$/.test(value)) {
                callback(new Error('请输入正确金额或数量，小数最多保留两位'));
            } else {
                callback();
            }
        };
        return {
            //校验规则
            addRule: {
                productCode: [{ required: true, message: '请输入商品编码', trigger: 'change' },
                    { min: 1, max: 20, message: '长度在 0 到 20 个字符', trigger: 'blur' }],
                productName: [{ required: true, message: '请输入商品名称', trigger: 'change' },
                    { min: 1, max: 20, message: '长度在 0 到 20 个字符', trigger: 'blur' }],
                productMoney: [{ required: true, message: '请输入商品价格', trigger: 'change' },
                    { validator: validatorNum, trigger: 'blur' }],
                // stock: [{ required: true, message: '请输入库存数', trigger: 'change' },
                //     { validator: validatorNum, trigger: 'blur' }],
                // warehouseCode: [{ required: true, message: '请输入仓库号', trigger: 'change' },
                //     { min: 1, max: 20, message: '长度在 0 到 20 个字符', trigger: 'blur' }],
                speck: [{ min: 1, max: 20, message: '长度在 0 到 20 个字符', trigger: 'blur' }]
            },
            //是否展示
            addVisible: false,
            imageUrl: '',//商品图片
            addForm: {
                productCode: '',
                productName: '',
                productMoney: '',
                speck: '',
                productUrl: '',
                status:'1'
            },
            BASIC_SERVER:global.BASIC_SERVER//请求服务名
        };
    },
    methods: {
        //初始化表单
        init() {
            //初始化清除表单验证
            this.addForm = {},
            this.$nextTick(() => {
                this.$refs['addForm'].clearValidate();
            })
            this.addVisible = true;
        },

        //新增
        saveAdd(addForm) {
            this.$refs[addForm].validate((valid) => {
                if (valid) {
                    this.addForm.status='1';
                    this.$http.post(this.BASIC_SERVER+'/productController/insertProduct.json', this.addForm).then(res => {
                        if (res.data.status) {
                            this.addVisible = false;//隐藏编辑框
                            this.$message.success('操作成功');
                            //调用父组件，刷新页面
                            this.$emit('get-data', null);
                            this.addForm = {};
                            this.imageUrl = '';//图片欢迎
                        }
                    });
                }
            });
        },
        //上传图片事件
        handleUploadImg(params) {
            let fd = new FormData();
            fd.append('file', params.file); //传给后台接收的名字 file
            this.$http.post(this.BASIC_SERVER+'/noticeController/uploadFile.json', fd, { headers: { 'Content-Type': 'multipart/form-data' } }).then(res => {
                console.log(res.data.status);
                if (res.data.status) {
                    this.$message.success('图片上传成功');
                    // 将图片地址给到表单.
                    console.log(res.data.data);
                    this.imageUrl=res.data.data.url;
                    this.addForm.productUrl=res.data.data.url;
                }
                params = '';
            });
        },

        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        }
    }
};
</script>

<style scoped>
.upload-demo {
    /*margin-left: 100px;*/
}
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}

.table {
    width: 100%;
    font-size: 14px;
}

.red {
    color: #ff0000;
}

.yellow{
    color: #E6A23C;
}

.mr10 {
    margin-right: 10px;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
